'use strict';
const dayjs = require("dayjs");
module.exports = app => {
    const { STRING, INTEGER } = app.Sequelize;
    const User = app.model.define(
        'User',
        {
            id: {type: INTEGER, primaryKey: true, autoIncrement: true},
            username: STRING(255),
            nickname: STRING(255),
            phone: STRING(255),
            id_no: STRING(255),
            address: STRING(255),
            // 中奖商品
            product_id: INTEGER,
            // 中奖记录
            lottery_record_id: INTEGER,
            created_at: {
                type: app.Sequelize.DATE,
                allowNull: true,
                get() {
                    return dayjs(this.getDataValue('created_at')).format('YYYY-MM-DD HH:mm:ss');
                },
            },
            updated_at: {
                type: app.Sequelize.DATE,
                allowNull: true,
                get() {
                    return dayjs(this.getDataValue('updated_at')).format('YYYY-MM-DD HH:mm:ss');
                },
            }
        },
        {
            tableName: 'users',
            timestamps: true, // 启用时间戳(createdAt, updatedAt)
        }
    );
    User.associate = function() {
       // 一个用户对应一个中奖记录
        app.model.User.hasOne(app.model.LotteryRecord, {
            foreignKey: 'user_id',
            targetKey: 'id',
            as: 'lotteryRecord',
        });
        // 一个用户对应一个产品
        app.model.User.belongsTo(app.model.Product, {
            foreignKey: 'product_id',
            targetKey: 'id',
            as: 'product',
        })
    }
    return User;
};
